<?php

namespace app\service\teach;

use app\exception\TokenInvalidException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use think\exception\HttpException;

class BaseService
{
    protected $timeout   = 60;
    protected $client;

    public function __construct($baseUrl)
    {
        $options = [
            'base_uri' => $baseUrl,
            'timeout'  => $this->timeout,
            'verify'   => false
        ];

        $this->client = new Client($options);
    }

    /**
     * 发送请求
     *
     * @param $path
     * @param $params
     * @param string $method
     * @param array $headers
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function call($path, $params, $method = 'GET', $options = [], $is_format = true)
    {
        try {
            if ($method == 'POST') {
                $options['form_params'] = $params;
            } else {
                $options['query'] = $params;
            }
            $response = $this->client->request($method, $path, $options);
            if ($is_format) {
                $content = $response->getBody()->getContents();
                if (strpos($content, "用户登录") !== false) {
                    throw new TokenInvalidException();
                }
                return $content;
            } else {
                return $response;
            }
        } catch (ClientException $exception) {
            throw new HttpException($exception->getCode(), "请求教务系统失败");
        }
    }

}
